import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
import 'package:xindong/common/xindong_methods.dart';
import 'package:xindong/manager/xindong_user_controller.dart';
import 'package:xindong/routes/call/controller/xindong_call_controller.dart';
import 'package:xindong/routes/call/dialog/xindong_call_option_sheet.dart';
import 'package:xindong/routes/common/xindong_invite_yemian.dart';
import 'package:xindong/routes/common/xindong_report_yemian.dart';
import 'package:xindong/routes/common/xindong_web_app_yemian.dart';
import 'package:xindong/routes/common/xindong_web_yemian.dart';
import 'package:xindong/routes/conversation/model/xindong_liaotian_detail_class.dart';
import 'package:xindong/routes/conversation/xindong_liaotian_yemian.dart';
import 'package:xindong/routes/conversation/xindong_liaotian_service_yemian.dart';
import 'package:xindong/routes/tab_bar/xindong_tab_bar_controller.dart';
import 'package:xindong/routes/tab_moments/model/xindong_dongtai_class.dart';
import 'package:xindong/routes/tab_moments/publish/xindong_dongtai_publish_yemian.dart';
import 'package:xindong/routes/user/auth/xindong_auth_face_tips_yemian.dart';
import 'package:xindong/routes/user/auth/xindong_auth_yemian.dart';
import 'package:xindong/routes/user/auth/xindong_auth_real_name_yemian.dart';
import 'package:xindong/routes/user/noble/xindong_noble_yemian.dart';
import 'package:xindong/routes/user/profile/xindong_profile_yemian.dart';
import 'package:xindong/routes/user/wallet/xindong_recharge_yemian.dart';
import 'package:xindong/routes/userspace/xindong_kongjian_yemian.dart';
import 'package:xindong/utils/xindong_text_util.dart';
import 'package:xindong/widgets/dialog/xindong_alert_message.dart';
import 'package:tencent_cloud_chat_uikit/tencent_cloud_chat_uikit.dart';

import '../routes/user/auth/xindong_auth_car_yemian.dart';
import '../routes/user/auth/xindong_auth_education_yemian.dart';
import '../routes/user/auth/xindong_auth_house_yemian.dart';
import '../routes/user/auth/xindong_auth_voice_yemian.dart';

class XinDongPageSingleton {
  // 避免重复、循环进入登录/空间/会话页，加标签判断
  bool? isInAccountYeMian; // 是否在登录页

  // 退出应用
  void exitApplication() {
    if (Platform.isIOS) {
      exit(0);
    } else {
      SystemNavigator.pop();
    }
  }

  // 到Tab页
  void jumpToTabBarYeMian({bool needJump = true}) {
    isInAccountYeMian = false;
    XinDongUserController.to.update([XinDongUserController.to.updateIdOfLoginStatus]);
    if (needJump) {
      popUntilYeMian("/");
    }
  }

  // 到登录
  void jumpToLoginYeMian({String? showTips}) {
    try {
      SmartDialog.dismiss(status: SmartStatus.allDialog);
      if (isInAccountYeMian != null && isInAccountYeMian == true) {
        return;
      }
      isInAccountYeMian = true;
      XinDongUserController.to.update([XinDongUserController.to.updateIdOfLoginStatus]);
      popUntilYeMian("/");
    } catch (e) {
      mCatchPrint(e);
    } finally {
      if (!TextUtil.isEmpty(showTips)) {
        XinDongAlertMessage.show(title: "登录失效", content: "$showTips", showCancelButton: false);
      }
    }
  }

  // 跳转Push页面
  Future<dynamic>? pushYeMian(Widget yemian) {
    return Get.to(yemian);
  }

  // 跳转Push页面
  // 可以参与实现：无跳转动画，不能侧滑返回，安卓按钮返回
  Future pushNoBackYeMian(Widget yemian) async {
    return Get.to(yemian, transition: Transition.noTransition, popGesture: false);
  }

  // 退出指定页面(如果找不到，则到'/'页)
  // 需要加'/'，如："/LoginYeMian"
  void popUntilYeMian(String routeName) {
    Get.until((route) => Get.currentRoute == routeName || Get.currentRoute == "/");
    if (Get.currentRoute != "/") {
      Get.back();
    }
  }

  // 退出到指定页面，然后跳转Push页面
  // 需要加'/'，如："/LoginYeMian"
  Future<dynamic>? popUntilThanPushYeMian(String popRouteName, Widget yemian) {
    return Get.offUntil(
      GetPageRoute(page: () => yemian),
      (route) => Get.currentRoute == popRouteName || Get.currentRoute == "/",
    );
  }

  // 呼叫
  void calling({required XinDongLiaoTianDetailClass? model}) {
    if (model == null || XinDongCallController.to.callSupport(model) == XinDongCallSupport.none) {
      // showToast("未开放通话");
      return;
    }
    XinDongCallOptionSheet.show(
      model: model,
      onSelect: (int callType) {
        XinDongCallController.requestCall(model.another, callType: callType);
      },
    );
  }

  // 根据名字跳转
  // onlyAuthYeMian true表示带有'auth'的都只跳转到认证列表页2，不需要到具体认证页
  void jumpWithName(String name, {bool onlyToAuthYeMian = false}) {
    if (onlyToAuthYeMian && name.contains("auth")) {
      pushYeMian(const XinDongAuthYeMian());
      return;
    }
    switch (name) {
      case "real_auth":
        pushYeMian(const XinDongAuthFaceTipsYeMian());
        break;
      case "name_auth":
        pushYeMian(const XinDongAuthRealNameYeMian());
        break;
      case "voice":
        pushYeMian(const XinDongAuthVoiceYeMian());
        break;
      case "education_auth":
        pushYeMian(const XinDongAuthEducationYeMian());
        break;
      case "car_auth":
        pushYeMian(const XinDongAuthCarYeMian());
        break;
      case "house_auth":
        pushYeMian(const XinDongAuthHouseYeMian());
        break;
      case "like":
      case "dymanic_comment":
        Get.back();
        XinDongTabBarController.to.jump(1);
        break;
      case "attention":
      case "defend":
        Get.back();
        XinDongTabBarController.to.jump(0);
        break;
      case "perfect_info":
        pushYeMian(const XinDongProfileYeMian());
        break;
      case "dymanic_day":
        pushYeMian(const XinDongDongTaiPublishYeMian());
        break;
      case "invite":
        pushYeMian(const XinDongInviteYeMian());
        break;
      default:
        showToast("暂不支持");
        break;
    }
  }

  // 贵族
  void openNoble() {
    pushYeMian(const XinDongNobleYeMian());
  }

  // 充值
  void toRechargeYeMian() {
    XinDongPageSingleton.instance.pushYeMian(const XinDongRechargeYeMian());
  }

  // 认证
  void toAuthYeMian() {
    XinDongPageSingleton.instance.pushYeMian(const XinDongAuthYeMian());
  }

  // 跳转到Web
  void jumpToWebYeMian({required String title, required String url, bool inApp = false}) async {
    if (inApp) {
      pushYeMian(XinDongWebAppYeMian(title: title, url: url));
    } else {
      pushYeMian(XinDongWebYeMian(title: title, url: url));
    }
  }

  // 跳转到客服
  void jumpToServiceYeMian() async {
    if (XinDongUserController.to.isUserCompleted) {
      pushYeMian(const XinDongLiaoTianServiceYeMian());
    }
  }

  // 到举报
  void jumpToReport({required userId, Function()? onDone}) {
    pushYeMian(XinDongReportYeMian(userId: userId));
  }

  // 到详情页
  Future<void> jumpWorldDetailsYeMian(
      {required Object object, bool isSpace = false, Function(XinDongDongTaiClass model)? deleteSuccessCallback}) async {
    XinDongDongTaiClass? worldClass;
    if (object is XinDongDongTaiClass) {
      worldClass = object;
    } else {
      // XinDongDongTaiClass? moment = await XinDongWorldHandle.requestDetailsData(did: object as int);
      // if (moment != null) {
      //   worldClass = moment;
      // }
    }
    if (worldClass == null) {
      showToast("该条动态异常！");
      return;
    }
    // pushYeMian(XinDongWorldDetailsYeMian(
    //   isSpace: isSpace,
    //   deleteSuccessCallback: deleteSuccessCallback,
    //   model: worldClass,
    // ));
  }

  // 到空间动态  space 成为好友点系统消息会条过来
  // XinDongBaseUser
  void jumpToSpace(dynamic userClass, {bool isChat = false}) async {
    // if (!XinDongAuditDialog.show()) {
    //   return;
    // }
    if (userClass == null) {
      showToast("参数错误，请联系客服！");
      return;
    }
    pushYeMian(XinDongKongJianYeMian(userId: userClass.uid, fromChat: isChat));
  }

  // 到IM
  // 白名单直接进，好友列表直接进V2TimConversation? conversation,
  void jumpToChatYeMian({dynamic userClass, V2TimConversation? conversation, bool fromKongJian = false}) async {
    // 没传入正确的参数
    if (userClass == null && conversation == null) {
      showToast('参数异常');
      return;
    }
    // 对方id
    final targetId = userClass?.uid ?? conversation?.userID ?? "";
    // 自己id
    final mineId = XinDongUserController.to.loginId;
    if (mineId == targetId) {
      showToast("不能和自己聊天");
      return;
    }

    // 获取会话
    if (conversation == null) {
      showLoading(maskColor: Colors.transparent);
      V2TimValueCallback<V2TimConversation> result =
          await TencentImSDKPlugin.v2TIMManager.v2ConversationManager.getConversation(conversationID: 'c2c_$targetId');
      conversation = result.data ??
          V2TimConversation(
            conversationID: 'c2c_${userClass.uid}',
            type: ConversationType.V2TIM_C2C,
            showName: userClass.getName,
            userID: '${userClass.uid}',
            groupID: null,
          );
      hideLoading();
    }
    pushYeMian(XinDongLiaoTianYeMian(conversation: conversation, fromKongJian: fromKongJian));
  }

  // ======== 单例
  // 工厂方法构造函数
  factory XinDongPageSingleton() => _getInstance();

  // instance的getter方法，singletonManager.instance获取对象
  static XinDongPageSingleton get instance => _getInstance();

  // 静态变量_instance，存储唯一对象
  static XinDongPageSingleton? _instance;

  // 获取对象
  static XinDongPageSingleton _getInstance() {
    _instance ??= XinDongPageSingleton._internal();
    return _instance!;
  }

  // 私有的自定义命名式构造方法，通过它实现一个类;
  // 子类不能继承internal
  // 不是关键字，可定义其他名字
  XinDongPageSingleton._internal() {
    //初始化(设置一些默认的)...
  }
}
